package com.goldze.mvvmhabit.ui.tab_bar.fragment.my;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.goldze.mvvmhabit.data.DemoRepository;
import com.goldze.mvvmhabit.ui.changePsw.ChangePsdActivity;
import com.goldze.mvvmhabit.ui.leave_recording.LeaveRecordingListActivity;
import com.goldze.mvvmhabit.ui.login.LoginActivity;
import com.goldze.mvvmhabit.ui.selectsdepartment.SelectDepartmentActivity;
import com.goldze.mvvmhabit.utils.RetrofitClient;
import com.goldze.mvvmhabit.utils.UserManager;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.MaterialDialogUtils;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class MyFragmentViewModel extends BaseViewModel<DemoRepository> {

    public SingleLiveEvent<String> dialogTitle = new SingleLiveEvent<>();

    public SingleLiveEvent<String> dialogHead = new SingleLiveEvent<>();

    public SingleLiveEvent refreshHead = new SingleLiveEvent<>();

    public MyFragmentViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    public BindingCommand my_head = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            dialogHead.setValue("");
        }
    });

    public BindingCommand my_department = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(SelectDepartmentActivity.class);
        }
    });

    public BindingCommand my_leave_recording = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(LeaveRecordingListActivity.class);
        }
    });

    public BindingCommand my_changpsw = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(ChangePsdActivity.class);
        }
    });

    public void exitApp(View view) {
        makeSureExit(view.getContext());
    }

    private void makeSureExit(Context content) {
        MaterialDialogUtils.showBasicDialog(content, "提示", "确认退出应用吗？")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        dialog.dismiss();
                    }
                }).onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(MaterialDialog dialog, DialogAction which) {
                UserManager.getAppManager().loginOut();
                startActivity(LoginActivity.class);
                finish();
            }
        }).show().setCanceledOnTouchOutside(false);
    }

    private void showDialogPhone(final Context content, final String photo) {
        MaterialDialogUtils.showBasicDialog(content, "提示", photo)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        dialog.dismiss();
                    }
                }).onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(MaterialDialog dialog, DialogAction which) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + photo);
                intent.setData(data);
                content.startActivity(intent);
            }
        }).show().setCanceledOnTouchOutside(false);
    }

    public void getCompanyInfo(final View view) {
        model.getCompanyInfo()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {
                        //请求成功
                        if (!response.isSuccess()) {
                            ToastUtils.showShort(response.getMsg());
                        } else {
                            if (response.getMsg() != null && !response.getMsg().isEmpty()) {
                                showDialogPhone(view.getContext(), response.getResponse().toString());
                            } else {
                                ToastUtils.showShort("获取验证码失败，请重新登录！");
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //关闭对话框
                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                        }
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }


    public void upLoadImageFile(String path) {
        model.uploadImg(path)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {
                        if (response.isSuccess()) {
                            upLoadHead(response.getResponse());
                        } else {
                            ToastUtils.showShort("上传头像失败！");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismissDialog();
                    }
                });
    }

    public void upLoadHead(final String path) {
        model.uploadHead(path)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse<Boolean>>() {
                    @Override
                    public void accept(BaseResponse<Boolean> response) throws Exception {
                        if (response.getResponse()) {
                            if (UserManager.getAppManager().getmUserInfo() != null) {
                                UserManager.getAppManager().getmUserInfo().setAvatar(RetrofitClient.baseUrl + path);
                            }
                            refreshHead.call();
                            ToastUtils.showShort("头像更新成功！");
                        } else {
                            ToastUtils.showShort("上传头像失败！");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismissDialog();
                    }
                });
    }

    public String getdepartmentName() {
        if (UserManager.getAppManager().isLogin()) {
            return UserManager.getAppManager().getmUserInfo().getDepartmentName();
        } else {
            return "";
        }
    }
}
